package com.example.boot.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 日志
 * 
 * @author ydx
 *
 */
@Aspect // 标注该类是该项目的切入点
@Component // 将该装在进容器
public class HttpAspect {
	private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

	// 切的那个点
	@Pointcut("execution(public * com.example.boot.order.controller.OrderController.*(..))")
	public void log() {
		logger.info("11111111111");
	}

	// 方法执行前
	// 也可以作为 @Before("execution(public *
	// com.example.boot.order.controller.OrderController.*(..))")
	//方法之前
	@Before("log()")//调用log
	public void log(JoinPoint joinPoint) {

		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();

		// 请求的路径|url
		logger.info("requestURL={}", request.getRequestURL());
		// 方式|method
		logger.info("method={}", request.getMethod());
		// 客户端地址|ip
		logger.info("ip={}", request.getRemoteAddr());
		// 类方法
		logger.info("mehtodClass={}",
				joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
		// 参数
		logger.info("args={}", joinPoint.getArgs());

	}

	// 方法之行后
	@After("log()")//
	public void doAfter() {
		logger.info("2222222222");
	}

	/**
	 * 传入的参数打印出來
	 * @param object
	 */
	@AfterReturning(returning = "object", pointcut = "log()")
	public void doAfterReturning(Object object) {
		logger.info("response={}", object.toString());

	}

}
